
package com.idealighter.game.games.horserace.manager;

import com.alibaba.fastjson.TypeReference;

import com.google.inject.Inject;
import com.google.inject.Singleton;

import com.idealighter.game.core.common.Game;
import com.idealighter.game.dictionary.dic.HorseRaceRoomDic;
import com.idealighter.game.dictionary.domain.HorseRaceRoomDomain;
import com.idealighter.game.games.horserace.struct.HorseRaceTable;
import com.idealighter.game.prizepool.manager.RoomPrizePoolMgrScript;
import com.idealighter.game.prizepool.struct.control.HorseRaceControl;
import com.idealighter.game.prizepool.struct.room.ControlStrategy;
import com.idealighter.game.prizepool.struct.room.RoomPrizePool;
import com.idealighter.utils.code.RandCodeUtil;

/**
 * 赛马控制 .
 *
 */
@Singleton
public class HorseRaceControlScript {

  private static final TypeReference<HorseRaceControl> HORSERACE_CONTROL_TYPE =
      new TypeReference<HorseRaceControl>() {};

  @Inject
  private HorseRaceRoomDic roomDic;
  @Inject
  private RoomPrizePoolMgrScript roomPrizePoolMgr;

  /**
   * 控制开奖 .
   *
   * @param table .
   */
  public boolean controlReward(HorseRaceTable table) {
    boolean win = false;
    RoomPrizePool seatRoomPrizePool =
        roomPrizePoolMgr.defaultRoomPrizePool(Game.HORCERACE, table.room.getId());
    if (seatRoomPrizePool != null) {
      ControlStrategy strategy = seatRoomPrizePool.abledControlStrategy();
      if (strategy != null) {
        HorseRaceControl horseControl = strategy.control(HORSERACE_CONTROL_TYPE);
        if (horseControl != null) {
          win = RandCodeUtil
              .random(horseControl.getLoseRatio() + horseControl.getWinRatio()) >= horseControl
                  .getLoseRatio();
        } else {
          win = RandCodeUtil.randomBoolean();
        }
      } else {
        win = RandCodeUtil.randomBoolean();
      }
    } else {
      win = RandCodeUtil.randomBoolean();
    }
    return win;
  }

  /**
   * 结算房间奖池 .
   *
   * @param table .
   */
  public void balanceControl(HorseRaceTable table) {
    long gold = convertGold(table.room.getId().intValue(), table.earn);
    RoomPrizePool seatRoomPrizePool =
        roomPrizePoolMgr.defaultRoomPrizePool(Game.HORCERACE, table.room.getId());
    if (seatRoomPrizePool != null) {
      long totalGold = convertGold(table.room.getId().intValue(), gold);
      long prize = seatRoomPrizePool.getPrize().get();
      prize += totalGold;
      seatRoomPrizePool.getPrize().getAndSet(prize);
    }
  }

  /**
   * 筹码换算金币,只会是多个金币等于一个筹码 .
   * 
   * @param roomId .
   * @param chips .
   */
  public long convertGold(int roomId, long chips) {
    HorseRaceRoomDomain roomDomain = roomDic.get(roomId);

    return chips * roomDomain.getProportionGold() / roomDomain.getProportionChips();
  }

}
